﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.Configuration;

using ThingPower.WeChat.MP;
using ThingPower.WeChat.MP.Helpers;
using ThingPower.WeChat.MP.AdvancedAPIs;
using ThingPower.WeChat.MP.AdvancedAPIs.OAuth;
using ThingPower.WeChat.MP.CommonAPIs;

namespace WeChatDemo.Controllers
{
    public class AccessTokenController : ApiController
    {
        string _appID = WebConfigurationManager.AppSettings["appID"];
        string _appSecret = WebConfigurationManager.AppSettings["appSecret"];
        string _appID_JSSDK = WebConfigurationManager.AppSettings["appID_JSSDK"];
        string _appSecret_JSSDK = WebConfigurationManager.AppSettings["appSecret_JSSDK"];
        readonly string _uploadImgPath = WebConfigurationManager.AppSettings["uploadFolderName"] + "\\images\\";

        // GET api/<controller>/{?code=123456789}
        public IHttpActionResult Get(string code)
        {
            //string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx71dae64ee25e0920&redirect_uri=http://www.shtraining.net/wx/openid.html&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
            
            try
            {
                var _accessTokenResult = OAuthApi.GetAccessToken(_appID, _appSecret, code);
                //var _userInfo = OAuthApi.GetUserInfo(_accessTokenResult.access_token, _accessTokenResult.openid);
                return Ok(_accessTokenResult.openid);

                ////return Ok($"openid : {_userInfo.openid}<br/>nickname : {_userInfo.nickname}");
                //return Ok(_userInfo);
            }
            catch(Exception ex) {
                return InternalServerError(ex);
            }
        }

        //获取微信JS-SDK的config参数
        public IHttpActionResult GetJSSDKConfig(string baseUrl, string querystring)
        {
            var _timestamp = JSSDKHelper.GetTimestamp();
            var _nonceStr = JSSDKHelper.GetNoncestr();
            string _ticket = JsApiTicketContainer.TryGetTicket(_appID_JSSDK, _appSecret_JSSDK);
            var _signature = JSSDKHelper.GetSignature(_ticket, _nonceStr, _timestamp, baseUrl + "?" + querystring + "&state=1");

            var config = new { appid = _appID_JSSDK, timestamp = _timestamp, nonceStr = _nonceStr, ticket = _ticket, signature = _signature, url = baseUrl + "?" + querystring + "&state=1" };
            return Ok(config);
            //return $"<span>{_appID}<span>{timeStamp}</span><span>{nonceStr}</span><span>{ticket}</span><span>{signature}</span>";
        }

        //从微信服务器下载多媒体文件
        [HttpGet]
        public string DownloadMedia(string media_id)
        {
            string _token = AccessTokenContainer.TryGetToken(_appID_JSSDK, _appSecret_JSSDK);
            string _downloadUrl = $"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={_token}&media_id={media_id}";

            WebClient _client = new WebClient();
            string _filePath = AppDomain.CurrentDomain.BaseDirectory + _uploadImgPath;
            string _fileName = DateTime.Now.ToFileTimeUtc() + ".jpg";
            _client.DownloadFile(new Uri(_downloadUrl), _filePath + _fileName);
            return _fileName;
        }

    }
}